package com.itheima.shop.proxy_review;

import com.itheima.shop.proxy.FileUpload;
import lombok.Data;
import org.springframework.beans.BeansException;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @program: design
 * @description:
 * @author: zhanghz001
 * @create: 2021-02-27 13:54
 **/
@Data
@Component
@ConfigurationProperties(prefix = "upload")
public class FileUploadProxyReview implements ApplicationContextAware {
    //注入application.yml中配置实例对应处理的文件类型
    private HashMap<String, List<String>> filemap;
    
    //注入Spring的容器对象ApplicationContext
    private ApplicationContext applicationContext;
    
    //注入映射配置
    public void setFilemap(HashMap<String, List<String>> filemap) {
        this.filemap = filemap;
    }
    
    /***
     * 上传方法
     * 接收文件对象：MultipartFile
     */
    public String upload(MultipartFile file) throws Exception {
        String filename = file.getOriginalFilename();
        //extName：后缀名  1.jpg->jpg
        String extension = StringUtils.getFilenameExtension(filename);
        byte[] bytes = file.getBytes();
        
        //循环filemap映射关系对象
        for (Map.Entry<String, List<String>> entry : filemap.entrySet()) {
            
            List<String> list = entry.getValue();
            //获取指定的value  mp4,avi  |  png,jpg
            for (String suffix : list) {
                if (suffix.equalsIgnoreCase(extension)) {
                    return applicationContext
                            .getBean(entry.getKey(), FileUpload.class)
                            .upload(bytes, extension);
                }
            }
        }
        return "";
    }
    
    //注入容器
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
